/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { SetupContext } from 'vue';
import { AvatarProps } from '../avatar.props';
import { ImageFile } from './types';

export function useFile(props: AvatarProps, context: SetupContext, allowTypes: string[]) {
    function getFileData($event: Event) {
        if (props.readonly) {
            return;
        }
        const fileInput = $event.target as HTMLInputElement;
        const selectedFiles = fileInput.files;
        if (!selectedFiles || !selectedFiles[0]) {
            return;
        }
        const fileType = selectedFiles[0].type;
        const isLtSize = selectedFiles[0].size / 1024 / 1024 < props.maxSize;
        if (allowTypes.indexOf(fileType) < 0) {
            // const typeErrorMessage = this.localeService.getValue('avatar.typeError');
            // this.notifyService.error({
            //     type: 'error',
            //     title: '',
            //     msg: typeErrorMessage
            // });
            // fileInput.value = '';
            return;
        }

        if (!isLtSize) {
            // const sizeErrorMessageTemplate = this.localeService.getValue('avatar.sizeError');
            // const sizeErrorMessage: string = sizeErrorMessageTemplate + props.maxSize + 'MB!';
            // this.notifyService.error({
            //     type: 'error',
            //     title: '',
            //     msg: sizeErrorMessage
            // });
            // fileInput.value = '';
            return;
        }
        // this.transformFile(selectedFiles[0]);
        fileInput.value = '';
    }

    function readSourceFile(sourceFile: File): Promise<{ state: string; content: string | ArrayBuffer | null }> {
        const result = new Promise<{ state: string; content: string | ArrayBuffer | null }>((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(sourceFile);
            reader.onload = () => {
                resolve({ state: 'done', content: reader.result });
            };
            reader.onerror = function () {
                reject({ state: 'error', content: reader.result });
            };
        });
        return result;
    }

    function updateImageSrc(imageSrc: string) {}

    function removeBase64(imageSrc: string) {}

    function transformFile(sourceFile: File) {
        // const subject = new Subject();
        const imageFile: ImageFile = {
            size: sourceFile.size,
            name: sourceFile.name,
            type: sourceFile.type,
            lastModified: String(sourceFile.lastModified)
        };
        readSourceFile(sourceFile)
            .then((result) => {
                if (result.state === 'done') {
                    // updateImageSrc(result.content as string);
                    // const imageFileContent = removeBase64(imageSrc);
                    // context.emit('change', imageFileContent);
                    // context.emit('touched');
                    // imageFile.state = result.state;
                    // imageFile.base64 = result.content as string;
                    // context.emit('imageChange', imageFile);
                }
            })
            .catch((reason) => {
                // const uploadErrorText = this.localeService.getValue('avatar.uploadError');
                // this.notifyService.error({
                //     type: 'error',
                //     title: '',
                //     msg: uploadErrorText
                // });
            });
    }
}
